import {storage} from "../../utils/storage";
var request = require('../../utils/request.js');
// QQ腾讯地图SDK
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var amapInstance;
var timerInstance;

const INIT_POLYLINE = {
	points: [
		{latitude: 40.040129,longitude: 116.274968},
		{latitude: 40.038974,longitude: 116.275214},
	],
	color: '#0000FF',
	width: 8,
	dottedLine: false,
	arrowLine: true,
	borderWidth: 2,
};
Page({
  data: {
    showDisNotice: false,
    distance: 0,
    Height: 0,
    scale: 12,
    latitude: "",
    longitude: "",
    polyline: [{
			...INIT_POLYLINE
		}],
  },

  onShow: function() {
    this.checkNotice()
  },

 // 检测当前距离以及当前电量是否符合要求
 checkNotice() {
    console.log('checkNotice') 
    var maxDis = storage.get('Distance') ||'1000'
    var maxCap = storage.get('Capacity') ||'100'
    console.log('checkNotice :' + (maxDis - this.data.distance)) 
    if (maxDis - this.data.distance < 0) {
      console.log('checkNotice :showDisNotice') 
      this.setData({
        showDisNotice: true,
        maxDis: maxDis
      })
    } else {
      this.setData({
        showDisNotice: false,
      })
    }

    if (maxCap - this.data.pertage > 0) {
      this.setData({
        showCapNotice: true,
        maxPer: maxCap
      })
    } else {
      this.setData({
        showCapNotice: false,
        maxPer: maxCap
      })
    }
  },

  onLoad: function (option) {
    console.log(this.data.polyline) 
    var that = this;
    // 每隔30s获取一下最新NBIOT定位信息
    timerInstance = setInterval(()=> {
      that.getData()
    }
    , 30000);

    var that = this
    // 初始化腾讯地图SDK
    amapInstance = new QQMapWX({
      key: 'EMHBZ-T6JWX-MHH46-TMODM-4IY77-RCBLM' //此处使用你自己申请的key
    })
    
    wx.getSystemInfo({
      success: function (res) {
        //设置map高度，根据当前设备宽高满屏显示
        that.setData({
          view: {
            Height: res.windowHeight
          }
        })
      }
    })
    // 获取定位信息
    that.getLocation();
  },

  onUnload : function() {
    if(timerInstance != null){
      clearInterval(timerInstance)
      timerInstance = null
    }
  },

  // 获取用户当前定位信息，以便用来计算安全距离
  getLocation: function() {
      var that = this
      // 获取当前定位信息
      wx.getLocation({
        type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
        success: function (res) {
            that.setData({
                latitude: res.latitude,
                longitude: res.longitude,
                'polyline[0].points[0]': {latitude: res.latitude,longitude: res.longitude},
                lat: res.latitude,
                lon: res.longitude
            })
        }
       })

      console.log(that.data.latitude, that.data.longitude) 
      // 获取NBIOT定位信息
      that.getData();
  },

  // 获取NBIOT定位信息，主要是通过OneNet的接口拉取回来
  getData: function () {
    var that = this;
    // onenet对应数据点
    var url = request.dataUrl + '/devices/686128127/datapoints';

    var params = {
      datastream_id: 'location,3311_0_5851',
      limit: 1
    }
    request.requestLoading(url, params, '正在加载数据', function (res) {
      console.log(res)
      var array = []
      array = res.data.datastreams
      if (array.length == 2) {
        array.forEach(element => {
          if (element.id == 'location') {
            var item = element.datapoints[0].value
            var result = [];
            // GPS定位转成符合腾讯地图显示的gc02坐标
            amapInstance.reverseGeocoder({
              location: {
                latitude: item.lat,
                longitude: item.lon,
              },
              coord_type: 1,
              success: function(res) {//成功后的回调
                console.log('wty');
                console.log(res);
                var res = res.result;
                
                result.push({
                  width: 12,
                  height: 25,
                  callout: {
                    content: 'NB-IOT设备',
                    padding: 10,
                    borderRadius: 2,
                    display: 'ALWAYS'
                  },
                  latitude: res.location.lat,
                  longitude: res.location.lng,
                  title: 'NB-IOT设备',
              });
              console.log(result)
              that.setData({
                'polyline[0].points[1]': {latitude: res.location.lat,longitude: res.location.lng},
                 lat_nb: res.location.lat,
                 lon_nb: res.location.lng,
                 markers: result
              });
              // 计算距离
              that.getDistance();
                }
            }
            );
          } else if(element.id == '3311_0_5851') {
            var item = element.datapoints[0].value
            that.data.pertage = item
            that.setData({
              pertage: item,
            });
            // 检测警告
            that.checkNotice()
          }
        });
      }
    }, function (res) { 
      wx.showToast({
        title: '加载数据失败',
        image: '../../image/fail.png'
      })
    })

  },

  // 跳转到配置页面
  goToConfig() {
    console.log('goToConfig');
    wx.navigateTo({
        url: '/pages/config/config',

    });
  },

  // 获取距离
  getDistance() {
    var that=this;
    //调用距离计算接口
    amapInstance.calculateDistance({
      //mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
      //from参数不填默认当前地址
      //获取表单提交的经纬度并设置from和to参数（示例为string格式）
      from: '', //若起点有数据则采用起点坐标，若为空默认当前地址
      to: [{
        latitude: this.data.lat_nb,
        longitude: this.data.lon_nb
      }], //终点坐标
      success: function(res) {//成功后的回调
        console.log(res);
        var res = res.result;
        var dis = [];
        for (var i = 0; i < res.elements.length; i++) {
          dis.push(res.elements[i].distance); //将返回数据存入dis数组，
        }
        that.data.distance = dis;
        that.setData({ //设置并更新distance数据
          distance: dis
        });
        that.checkNotice()
      },
      fail: function(error) {
        console.error(error);
      },
      complete: function(res) {
        console.log(res);
      }
  });
  }
})